package com.jdz.gxq.info.admin.estate.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.jdz.gxq.info.admin.estate.bo.Estate;
import com.jdz.gxq.info.admin.estate.form.EditEstateForm;
import com.jdz.gxq.info.admin.estate.service.EstateService;
import com.jdz.gxq.info.admin.file.service.FileService;
import com.jdz.gxq.info.common.action.CommonAction;
import com.jdz.gxq.info.common.constant.Constant;

public class SaveEstateAction extends CommonAction {

	private EstateService estateService = null;
	
	private FileService fileService = null;
	 
	public ActionForward doExecute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws java.lang.Exception {
		
		EditEstateForm editEstateForm = (EditEstateForm) form;
		
		Estate estate = editEstateForm.getEstate();
		
		// estate名重复验证(其他后台逻辑验证也类似处理)
		if (!estateService.checkEstateName(estate, 2)) {
			ActionMessages messages = new ActionMessages();
			messages.add("estate.enterpriseName", new ActionMessage("error.estateNameExisted"));
			addErrors(request, messages);
			return mapping.getInputForward();
		}
		
		estate.setModifiedBy(getUserId(request));
		
		estateService.updateEstate(estate);
		
		String[] oldPicIds = editEstateForm.getOldEnterprisePic().split(",");
		
		String newPicIds = estate.getEnterprisePicture();
		
		// 文件上传相对路径
		String relativePath = Constant.IMAGE_PATH_ESTATE;
		
		// 取得的物理路径
		String realPath = request.getSession().getServletContext().getRealPath(relativePath);
				
		// 比较已经删除了的picid,将其信息删除(图片表和对应图片)
		for (String oldPicId : oldPicIds) {
			
			// 如果原来的pic不存在，则进行删除操作
			if (newPicIds.length() == newPicIds.replace(oldPicId, "").length()) {
				fileService.deleteImageInfo(oldPicId, realPath);
			}
		}
		
		return mapping.findForward("success");
	}

	public void setEstateService(EstateService estateService) {
		this.estateService = estateService;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}
}

